package com.archetypus.projectschedule.common.data;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.archetypus.projectschedule.common.Configuration;
import com.archetypus.projectschedule.common.ServiceLocator;
import com.archetypus.projectschedule.common.ServiceLocatorException;
import com.archetypus.projectschedule.common.data.activities.ActivityDAO;
import com.archetypus.projectschedule.common.data.activities.MySqlActivityDAO;
import com.archetypus.projectschedule.common.data.involvements.InvolvementDAO;
import com.archetypus.projectschedule.common.data.involvements.MySqlInvolvementDAO;
import com.archetypus.projectschedule.common.data.people.MySqlPersonDAO;
import com.archetypus.projectschedule.common.data.people.PersonDAO;
import com.archetypus.projectschedule.common.data.projects.MySqlProjectDAO;
import com.archetypus.projectschedule.common.data.projects.ProjectDAO;
import com.archetypus.projectschedule.common.exceptions.ProjectSchedulerException;

public class MySqlDAOFactory extends DAOFactory {
	
	private static DataSource dataSource;
	private static String jndiDS;
	
	public MySqlDAOFactory(){
		jndiDS = Configuration.getInstance().get("jndiDS");
	}
	
	public static Connection createConnection() throws ProjectSchedulerException{
		
		if(dataSource == null){
			try{
				dataSource = (DataSource) ServiceLocator.getInstance().lookup(jndiDS);
			}catch(ServiceLocatorException ex){
				ex.printStackTrace();
				throw new ProjectSchedulerException("Could not get datasource");
			}
		}
		
		Connection conn = null;
		try{
			conn = dataSource.getConnection();
		}catch(SQLException ex){
			ex.printStackTrace();
			throw new ProjectSchedulerException("Could not create connection");
		}
		
		return conn;
	}
	
	@Override
	public ActivityDAO getActivityDAO() {
		return new MySqlActivityDAO();
	}

	@Override
	public InvolvementDAO getInvolvementDAO() {
		return new MySqlInvolvementDAO();
	}

	@Override
	public PersonDAO getPersonDAO() {
		return new MySqlPersonDAO();
	}

	@Override
	public ProjectDAO getProjectDAO() {
		return new MySqlProjectDAO();
	}

}
